<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Acceso extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->form_data = new stdClass();
        $this->load->helper('navigation');
    }

    public function index() {
        $this->load->view('login_view');
    }

    public function validar() {
        if (isset($_POST['usuario'])) {
            $usu = $_POST["usuario"];
            $pass = $_POST["clave"];
            $this->form_validation->set_rules('usuario', 'usuario', 'required|min_lenght[5]|max_lenght[20]');
            $this->form_validation->set_rules('clave', 'clave', 'required');

            if ($this->form_validation->run() == FALSE) {
                $this->index();
            } else {

                $params = array($usu, $pass);
                $this->load->model("usuario_model");
                $result = $this->usuario_model->acceso($params);
                if ($result) {
                    $sesion_data = array(
                        'codigo' => $result{0}['cod_usu'],
                        'nombre' => $result{0}['nom_emp'],
                        'apellido' => $result{0}['ape_emp'],
                        'idSuc' => $result{0}['sucursal_id'],
                        'sucursal' => $result{0}['desc_suc'],
                        'tipo' => $result{0}['tipousuario_id'],
                        'usuario' => $usu,
                        'clave' => $pass
                    );
                    $this->session->set_userdata($sesion_data);

                    $this->inicio();
                } else {
                    $this->form_data->msj = "Usuario o clave incorrecta, por favor vuelva a intentarlo";
                    $this->index();
                }
            }
        } else {
            if (isset($this->session->userdata['nombre'])) {
                $this->inicio();
            } else {
                $this->index();
            }
        }
    }

    public function inicio() {
        //$menu["inicio"] = 'active open';
        $this->load->model("panel_model");
        $this->sesion();
        $this->pagina('inicio_view', array());
    }

    public function panel($user = 0) {
        $this->load->model("panel_model");
        $this->load->model("usuario_model");
        $params2 = array($user, 2);
        $menu2 = $this->panel_model->menu($params2);
        if ($user == 0) {
            $data["users"] = $this->usuario_model->usuarios();
            $this->pagina('panel_view', $data);
        } else {
            echo "<input type='hidden' id='totalPag' value='".  count($menu2)."'>";
            echo menu_permisos_ul($menu2);
        }
    }

    public function permisos() {
        $this->load->model("panel_model");
        $paginas = json_decode($_POST["paginas"]);
        $user = $_POST["users"];
        $valor = $this->panel_model->guardarPermisos($user, $paginas);
        echo json_encode($valor);
    }

    public function empleado() {
        $this->load->model("panel_model");
        $data["empleados"] = $this->panel_model->lstEmpleados(0);
        $this->pagina('empleado_view', $data);
    }

    public function formEmpleado($cod) {
        $this->load->model("logistica/servicios_model");
        $data['sucursales'] = $this->servicios_model->combo2('sucursal', 0);
        $data['tipousu'] = $this->servicios_model->combo2('tipousuario', 0);
        $this->setValEmpleado($cod);
        $this->pagina('formEmpleado_view', $data);
    }

    public function setValEmpleado($cod) {
        if ($cod == 0) {
            $this->form_data->id = $cod;
            $this->form_data->nom_emp = "";
            $this->form_data->ape_emp = "";
            $this->form_data->dni = "";
            $this->form_data->fec_nac = "";
            $this->form_data->sexo = "";
            $this->form_data->dir = "";
            $this->form_data->tel = "";
            $this->form_data->suc_emp = "";
            $this->form_data->tipousuario = "";
        } else {
            date_default_timezone_set('UTC');
            $this->load->model("panel_model");
            $empleados = $this->panel_model->lstEmpleados($cod);
            $fecha = $empleados{0}->fec_nac;
            $mi_fecha = date("d-m-Y", strtotime($fecha));
            $this->form_data->id = $empleados{0}->id_emp;
            $this->form_data->nom_emp = $empleados{0}->nom_emp;
            $this->form_data->ape_emp = $empleados{0}->ape_emp;
            $this->form_data->dni = $empleados{0}->dni_emp;
            $this->form_data->fec_nac = $mi_fecha;
            $this->form_data->sexo = $empleados{0}->sexo;
            $this->form_data->dir = $empleados{0}->dir_emp;
            $this->form_data->tel = $empleados{0}->tel_emp;
            $this->form_data->suc_emp = $empleados{0}->sucursal_id;
            $this->form_data->tipousuario = $empleados{0}->tipousuario_id;
        }
    }

    public function registrarEmpleado() {
        date_default_timezone_set('UTC');
        $this->load->model("panel_model");
        $fecha = $_POST["fecNac"];
        $mi_fecha = date("Y-m-d", strtotime($fecha));
        $params = array($_POST["nombre"], $_POST["apellido"], $_POST["dni"], $mi_fecha,
            $_POST["sexo"], $_POST["dir"], $_POST["tel"], $_POST["suc"], $_POST["tipo"], $_POST["idEmp"]);
        $this->panel_model->IU_Empleado($params);
        if ($_POST["pag"] == "empl") {
            $this->formEmpleado(0);
        } else {
            $this->cerrarSesion();
        }
    }

    public function perfil() {
        $this->load->model("logistica/servicios_model");
        $data['sucursales'] = $this->servicios_model->combo2('sucursal', 0);
        $data['tipousu'] = $this->servicios_model->combo2('tipousuario', 0);
        $cod = $this->session->userdata['codigo'];
        $this->form_data->user = $this->session->userdata['usuario'];
        $this->setValEmpleado($cod);
        $this->pagina('perfil_view', $data);
    }

    public function actualizarCuenta() {
        $this->load->model("usuario_model");
        $cod = $this->session->userdata['codigo'];
        $clave = $this->session->userdata['clave'];
        if ($_POST["clave"] == $clave) {
            $params = array($_POST["usuario"], $_POST["newclave"], $cod);
            $this->usuario_model->U_Cuenta($params);
            $valor = true;
        } else {
            $valor = false;
        }
        echo json_encode($valor);
    }

    private function pagina($vista, $data) {
        $this->sesion();
        $this->load->model("panel_model");
        $menu["logistica"] = "active open";
        $user = $this->session->userdata['codigo'];
        $params = array($user, 1);
        $menu["menu"] = $this->panel_model->menu($params);
        $this->load->view('estructura/head');
        $this->load->view('estructura/madmin', $menu);
        $this->load->view('intranet/' . $vista, $data);
        $this->load->view('estructura/footer');
    }

    private function sesion() {
        $this->form_data->nom = $this->session->userdata['nombre'];
        $this->form_data->ape = $this->session->userdata['apellido'];
        $this->form_data->suc = $this->session->userdata['sucursal'];
    }

    public function cerrarSesion() {
        $this->session->sess_destroy();
        $this->index();
    }

}
